//
//  YNBroadcastChat.m
//  Messenger
//
//  Created by iOS on 15/6/8.
//  Copyright (c) 2015年 YN-APP-iOS. All rights reserved.
//

#import "YNBroadcastChat.h"
#import "YNTwoPeopleChat.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "FMDatabaseAdditions.h"
#import "YNIMTool.h"
#import "YNIMFrameworkMacro.h"

@implementation YNBroadcastChat

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    if (!value){
        if ([key isEqualToString:@"messageType"]){
            self.messageType=0;
        }else if ([key isEqualToString:@"isRead"]){
            self.isRead=0;
        }
    }
}

+ (NSString *)packetId
{
    return @"packetId";
}

+ (NSString *)subject
{
    return @"subject";
}

+ (NSString *)fromUserNo
{
    return @"fromUserNo";
}

+ (NSString *)toUserNo
{
    return @"toUserNo";
}

+ (NSString *)messageType
{
    return @"messageType";
}

+ (NSString *)message
{
    return @"message";
}

+ (NSString *)mTime
{
    return @"mTime";
}

+ (NSString *)senderName
{
    return @"senderName";
}

+ (NSString *)recipient
{
    return @"recipient";
}

+ (NSString *)headerUrl
{
    return @"headerUrl";
}

+ (NSString*)isRead{
    return @"isRead";
}

+ (NSString *)tableName
{
    return @"BroadcastChat";
}

+(NSString *)messageContinuousKey
{
    return @"messageContinuousKey";
}

+(NSString *)isMessageContinuous
{
    return @"isMessageContinuous";
}


- (NSArray *)insertParam
{
    return @[[YNIMTool nilFilter:self.packetId],
             [YNIMTool nilFilter:self.subject],
             [YNIMTool nilFilter:self.fromUserNo],
             [YNIMTool nilFilter:self.toUserNo],
             [NSNumber numberWithInt:self.messageType],
             [YNIMTool nilFilter:self.message],
             [YNIMTool nilFilter:self.mTime],
             [YNIMTool nilFilter:self.senderName],
             [YNIMTool nilFilter:self.recipient],
             [YNIMTool nilFilter:self.headerUrl],
             [NSNumber numberWithBool:self.isRead],
             [YNIMTool nilFilter:self.messageContinuousKey],
             [NSNumber numberWithInteger:self.isMessageContinuous]];
}

+ (BOOL)creatBroadcastMesageTableInDatabase:(FMDatabase *)db
{
    if ([db tableExists:[YNBroadcastChat tableName]]) {
        return YES;
    }
    NSString *creatBroadcastSql = [NSString stringWithFormat:@"%@%@(%@ varchar(30) NOT NULL PRIMARY KEY, %@ varchar(30), %@ varchar(30), %@ varchar(30), %@ INTEGER, %@ varchar(100), %@ varchar(30), %@ varchar(30), %@ varchar(100), %@ varchar(50), %@ INTEGER, %@ INTEGER, %@ INTEGER)",
                                   CREATE_TABLE,
                                   [YNBroadcastChat tableName],
                                   [YNBroadcastChat packetId],
                                   [YNBroadcastChat subject],
                                   [YNBroadcastChat fromUserNo],
                                   [YNBroadcastChat toUserNo],
                                   [YNBroadcastChat messageType],
                                   [YNBroadcastChat message],
                                   [YNBroadcastChat mTime],
                                   [YNBroadcastChat senderName],
                                   [YNBroadcastChat recipient],
                                   [YNBroadcastChat headerUrl],
                                   [YNBroadcastChat isRead],
                                   [YNBroadcastChat messageContinuousKey],
                                   [YNBroadcastChat isMessageContinuous]];
    BOOL result = [db executeUpdate:creatBroadcastSql];
    return result;
}
/**HX** 在表中新增一个列（字段） **/
+ (BOOL)insertOneColumnInDatabase:(FMDatabase*)db ColumnName:(NSString*)name columnDataType:(NSString*)type{
    if (![db columnExists:name inTableWithName:[YNBroadcastChat tableName]]) {
        //列name在表中不存在，所以加入
        BOOL result= [db executeUpdate:[NSString stringWithFormat:@"%@ %@ add %@ %@",ALTER_TABLE,[YNBroadcastChat tableName],name,type]];
        return result;
    }
    return YES;
}
/**HX** 根据packId判断数据库是否存在这条消息 **/
+ (BOOL)determineBroadcastMessageTableWithPackId:(NSString *)packId Database:(FMDatabase *)db
{
    NSString *queryUserNoSql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ LIKE '%@'",
                                [YNBroadcastChat tableName],
                                [YNBroadcastChat packetId],
                                packId];
    FMResultSet *rs = [db executeQuery:queryUserNoSql];
    
    BOOL result = NO;
    while ([rs next])
    {
        result = YES;
    }
    [rs close];
    return result;
}

/**JC** 根据packId判断数据库是否存在这条消息 **/
+(NSArray*)queryBroadcastMessageTableWithPackId:(NSString *)packId Database:(FMDatabase *)db
{
    NSString *queryUserNoSql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = '%@'",
                                [YNBroadcastChat tableName],
                                [YNBroadcastChat packetId],
                                packId];
    FMResultSet *rs = [db executeQuery:queryUserNoSql];
    NSMutableArray *broadcastChatByKeywordArray = [NSMutableArray array];
    while ([rs next]) {
        YNBroadcastChat * broadcastChat = [[YNBroadcastChat alloc] init];
        if (![YNIMTool isEmptyDictionary:[rs resultDictionary]]) {
            [broadcastChat setValuesForKeysWithDictionary:[rs resultDictionary]];
            [broadcastChatByKeywordArray addObject:broadcastChat];
        }
    }
    [rs close];
    
    return broadcastChatByKeywordArray;
}

- (BOOL)insertBroadcastMessageInDatabase:(FMDatabase *)db
{
    BOOL isBroadcastMessageExist =  [YNBroadcastChat determineBroadcastMessageTableWithPackId:self.packetId Database:db];
    BOOL result=YES;
    
    //messageContinuousKey 取值为最近第一条消息的messageContinuousKey值//
    if([YNIMTool isEmptyString:self.messageContinuousKey])
    {
        NSArray * broadcastArray  =[YNBroadcastChat queryBroadcastChatTopInfoWithmTime:nil numberCount:1 Database:db];
        if([YNIMTool isEmptyArray:broadcastArray])
        {
            //没有消息，key值取新的GUID值
            self.messageContinuousKey = [YNIMTool getGUID];
        }
        else
        {
            YNBroadcastChat * broadcastChat = broadcastArray.firstObject;
            if([YNIMTool isEmptyString:broadcastChat.messageContinuousKey])
            {
                //没有消息，key值取新的GUID值
                self.messageContinuousKey = [YNIMTool getGUID];
            }
            else
            {
                self.messageContinuousKey = broadcastChat.messageContinuousKey;
            }
            
        }
    }
    //messageContinuousKey 取值为最近第一条消息的messageContinuousKey值//
    
    if (!isBroadcastMessageExist) {
        NSString *fieldString = [NSString stringWithFormat:@"%@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@, %@",
                                 [YNBroadcastChat packetId],
                                 [YNBroadcastChat subject],
                                 [YNBroadcastChat fromUserNo],
                                 [YNBroadcastChat toUserNo],
                                 [YNBroadcastChat messageType],
                                 [YNBroadcastChat message],
                                 [YNBroadcastChat mTime],
                                 [YNBroadcastChat senderName],
                                 [YNBroadcastChat recipient],
                                 [YNBroadcastChat headerUrl],
                                 [YNBroadcastChat isRead],
                                 [YNBroadcastChat messageContinuousKey],
                                 [YNBroadcastChat isMessageContinuous]];
        NSString *insertBroadcastSql = [NSString stringWithFormat:@"%@%@ (%@) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", INSERT_TABLE, [YNBroadcastChat tableName], fieldString];
        
        result = [db executeUpdate:insertBroadcastSql withArgumentsInArray:[self insertParam]];
    }else{
        /**HX** 存在这条广播就更新已读未读状态-其他的没必要更新 **/
        NSString *updateIsReadSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ? WHERE %@ = ?",
                                     [YNBroadcastChat tableName],
                                     [YNBroadcastChat isRead],
                                     [YNBroadcastChat packetId]];
        BOOL result = [db executeUpdate:updateIsReadSql,[NSNumber numberWithBool:self.isRead],self.packetId];
        
        //存在这条消息，并且isMessageContinuous是连续YES
        //修改所有的值为messageContinuousKey，isMessageContinuous相同的为最新的key值
        if(isBroadcastMessageExist == YES && self.isMessageContinuous == YES)
        {
            NSArray * broadCastArray = [YNBroadcastChat queryBroadcastMessageTableWithPackId:self.packetId Database:db];
            if(![YNIMTool isEmptyArray:broadCastArray])
            {
                YNTwoPeopleChat * oldBroadCast = broadCastArray.firstObject;
                //1,修改当前数据信息
                result= [YNBroadcastChat updateBroadChatMessageContinuousTableWithPackId:self.packetId messageContinuousKey:self.messageContinuousKey inDatabase:db];
                //2，修改所有的messageContinuousKey相同值，isMessageContinuous为YES的数据。
                if(![YNIMTool isEmptyString:oldBroadCast.messageContinuousKey])
                {
                    result = [YNBroadcastChat updateBroadChatAllMessageContinuousWithMessageContinuousKey:self.messageContinuousKey oldMessageContinuousKey:oldBroadCast.messageContinuousKey inDatabase:db];
                }
                
            }
        }
        
        return result;
    }
    return result;
}

+ (BOOL)updateIsReadToReadInDatabase:(FMDatabase*)db packetId:(NSString*)Id{
    BOOL isBroadcastMessageExist =  [YNBroadcastChat determineBroadcastMessageTableWithPackId:Id Database:db];
    BOOL result=YES;
    if (isBroadcastMessageExist) {
        NSString *updateIsReadSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = ? WHERE %@ = ?",
                                     [YNBroadcastChat tableName],
                                     [YNBroadcastChat isRead],
                                     [YNBroadcastChat packetId]];
        result = [db executeUpdate:updateIsReadSql,[NSNumber numberWithBool:YES],Id];
    }
    return result;
}

/**
 JC修改消息漫游
 
 @param packId id
 @param messageContinuousKey key
 @param db db
 @return 返回结果
 */
+(BOOL)updateBroadChatMessageContinuousTableWithPackId:(NSString *)packId messageContinuousKey:(NSString *)messageContinuousKey inDatabase:(FMDatabase *)db
{
    NSString *updateTwoPeopleChatSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = '%@', %@ = %@ WHERE %@ = '%@'",
                                        [YNBroadcastChat tableName],
                                        [YNBroadcastChat messageContinuousKey],
                                        messageContinuousKey,
                                        [YNBroadcastChat isMessageContinuous],
                                        [NSNumber numberWithInt:YES],
                                        [YNBroadcastChat packetId],
                                        packId];
    
    BOOL result = [db executeUpdate:updateTwoPeopleChatSql];
    return  result;
}




/**
 JC修改所有消息漫游信息
 
 @param messageContinuousKey 新的key
 @param oldMessageContinuousKey 旧的key
 @param db db
 @return 返回结果
 */
+(BOOL)updateBroadChatAllMessageContinuousWithMessageContinuousKey:(NSString *)messageContinuousKey oldMessageContinuousKey:(NSString *)oldMessageContinuousKey inDatabase:(FMDatabase *)db
{
    NSString *updateTwoPeopleChatSql = [NSString stringWithFormat:@"UPDATE %@ SET %@ = '%@' WHERE %@ = '%@' AND %@ = %@",
                                        [YNBroadcastChat tableName],
                                        [YNBroadcastChat messageContinuousKey],
                                        messageContinuousKey,
                                        [YNBroadcastChat messageContinuousKey],
                                        oldMessageContinuousKey,
                                        [YNBroadcastChat isMessageContinuous],
                                        [NSNumber numberWithInt:YES]];
    
    BOOL result = [db executeUpdate:updateTwoPeopleChatSql];
    return  result;
}


+ (BOOL)deleteALLBroadcastInDatabase:(FMDatabase *)db
{
    if (![db tableExists:[YNBroadcastChat tableName]]) {
        return YES;
    }
    NSString *deleteAllBroadcastSql = [NSString stringWithFormat:@"DELETE FROM %@ ", [YNBroadcastChat tableName]];
    BOOL result = [db executeUpdate:deleteAllBroadcastSql];
    return result;
}

+ (BOOL)deleteBroadcastWithPacketId:(NSString *)packetId inDatabase:(FMDatabase *)db
{
    NSString *deleteBroadcastSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?", [YNBroadcastChat tableName], [YNBroadcastChat packetId]];
    
    BOOL result = [db executeUpdate:deleteBroadcastSql,packetId];
    
    return result;
}

+ (NSArray *)queryBroadcastWithStartIndex:(NSInteger)start
                                 endIndex:(NSInteger)end
                               inDatabase:(FMDatabase *)db
{
    NSString *orderByStr = [NSString stringWithFormat:@" ORDER BY %@ DESC", [YNBroadcastChat mTime]];//DESC：倒叙取出值
    
    NSString *queryBroadcastSql = [NSString stringWithFormat:@"SELECT * FROM %@ %@ LIMIT %ld, %ld",
                                   [YNBroadcastChat tableName],
                                   orderByStr,
                                   start,
                                   end];
    NSMutableArray *broadcastArray = [NSMutableArray array];
    
    FMResultSet *rs = [db executeQuery:queryBroadcastSql];
    
    while ([rs next])
    {
        YNBroadcastChat *broadcast = [[YNBroadcastChat alloc] init];
        NSMutableDictionary*dataDic=[NSMutableDictionary dictionaryWithDictionary:[rs resultDictionary]];
        
        if ([YNIMTool isEmptyObject:dataDic[@"isRead"]]) {
            [dataDic setObject:@(0) forKey:@"isRead"];
        }
        if ([YNIMTool isEmptyObject:dataDic[@"messageType"]]) {
            [dataDic setObject:@(0) forKey:@"messageType"];
        }
        
        if (![YNIMTool isEmptyDictionary:dataDic]) {
            [broadcast setValuesForKeysWithDictionary:dataDic];
        }
        
        [broadcastArray insertObject:broadcast atIndex:0];
    }
    
    [rs close];
    
    return broadcastArray;
}

/**
 用于消息漫游判断
 查询最近多少条信息
 
 @param UserNo 聊天对方账号
 @param sendTime 这个时间之前的多少条数据，nil：最近多少条数据
 @param numberCount 查询多少条数据
 @param db db
 @return 返回结果
 */
+(NSArray *)queryBroadcastChatTopInfoWithmTime:(NSString *)mTime numberCount:(NSInteger)numberCount Database:(FMDatabase *)db
{
    NSString *queryTwoPeopleChatByKeywordSql;
    //sendTime为空，获取最近numberCount条数据
    if([YNIMTool isEmptyString:mTime])
    {
        queryTwoPeopleChatByKeywordSql = [NSString stringWithFormat:@"SELECT * FROM  %@  ORDER BY %@ DESC limit %ld",[YNBroadcastChat tableName],[YNBroadcastChat mTime],numberCount];
    }
    //sendTime有值，获取sendTime时间之前numberCount条数据
    else
    {
        queryTwoPeopleChatByKeywordSql = [NSString stringWithFormat:@"SELECT * FROM  %@ WHERE  %@ < datetime('%@') OR %@ = '%@' ORDER BY %@ DESC limit %ld",[YNBroadcastChat tableName],[YNBroadcastChat mTime],mTime,[YNBroadcastChat mTime],mTime,[YNBroadcastChat mTime],numberCount];
    }
    
    FMResultSet *rs = [db executeQuery:queryTwoPeopleChatByKeywordSql];
    NSMutableArray *broadcastChatByKeywordArray = [NSMutableArray array];
    while ([rs next]) {
        YNBroadcastChat * twoPeopleChat = [[YNBroadcastChat alloc] init];
        if (![YNIMTool isEmptyDictionary:[rs resultDictionary]]) {
            [twoPeopleChat setValuesForKeysWithDictionary:[rs resultDictionary]];
            [broadcastChatByKeywordArray addObject:twoPeopleChat];
        }
    }
    [rs close];
    
    return broadcastChatByKeywordArray;
}


@end
